#include "../include/SSEncrypt.h"
#include "rdSha1.h"
#include "core/Utility.h"

namespace qb {

	static char hex_map[16] = {
		'0'	,	'1'	,	'2'	,	'3'	,
		'4'	,	'5'	,	'6'	,	'7'	,
		'8'	,	'9'	,	'A'	,	'B'	,
		'C'	,	'D'	,	'E'	,	'F'
	} ;

	int hex_sprintf(char * strbuf , char val)
	{
		strbuf[0] = hex_map[(val >> 4) & 0XF] ;
		strbuf[1] = hex_map[val & 0XF] ;
		strbuf[2] = '\0' ;
		return 2 ;
	}

    bool encrypt_sha1(const unsigned char * buffer , uint32_t buflen , unsigned char * digest)
	{
		SHA1Context ct;
		SHA1Reset(&ct);
		if(SHA1Input(&ct,buffer,buflen) != shaSuccess)
			return false ;

		return SHA1Result(&ct,digest) == shaSuccess ;
	}

	bool CheckMd5(const char* buf,int len,const char*Md5)
	{
		//计算SHA1值
		char hex[64] = { 0 };
		memset(hex,0,sizeof(hex));
		int hlen = 0,olen = 0 ;
        unsigned char digest[20] ;
		memset(digest , 0 , sizeof(digest)) ;
        if(encrypt_sha1((unsigned char *)buf , len , digest) == true)
		{
			for(int idx = 0 ; idx < 20 ; idx++)
			{
                hlen += hex_sprintf(hex + hlen , (char)digest[idx]) ;
			}

			hex[hlen] = '\0' ;
		}

        if(strcmp(Md5,hex) == 0) return true;
        else return false;
	}

	bool GetMd5(char* buf,int len,char*outMd5,int capcity)
	{
		//计算SHA1值
		char hex[64] = { 0 };
		memset(hex,0,sizeof(hex));
		int hlen = 0,olen = 0 ;
        unsigned char digest[20] ;
		memset(digest , 0 , sizeof(digest)) ;
        if(encrypt_sha1((unsigned char *)buf , len , digest) == true)
		{
			for(int idx = 0 ; idx < 20 ; idx++)
			{
                hlen += hex_sprintf(hex + hlen , (char)digest[idx]) ;
			}

			hex[hlen] = '\0' ;
		}
		FIELDCOPYN(outMd5, capcity, hex);
        return true;
	}
}
